<?php

/**
 * Menu(菜单管理)
 */
namespace app\htsoft\controller;
use think\Controller;
use think\Url;
use think\Config;
use think\Page;
use think\Verify;
use think\Db;
class Menu extends \app\common\controller\Base {

	/**
	 *  显示菜单
	 */
	public function index() {
		$_SESSION['admin_menu_index']="Menu/index";
		$result = Db::name("Menu") ->where(['app'=>'Htsoft']) ->order(array("listorder" => "ASC"))->select();
		$tree = new \think\Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';

		$newmenus=array();
		foreach ($result as $m){
			$newmenus[$m['id']]=$m;
		}

		foreach ($result as $n=> $r) {
			$result[$n]['level'] = $this->_get_level($r['id'], $newmenus);
			$result[$n]['parentid_node'] = ($r['parentid']) ? ' class="child-of-node-' . $r['parentid'] . '"' : '';
			$result[$n]['str_manage'] = '<a href="' . Url::build("Menu/add",["parentid" => $r['id']])  . '" class="layui-btn  layui-btn-normal layui-btn-xs">添加子菜单</a>
            										     <a href="' . Url::build("Menu/edit", ["id" => $r['id']])  . '" class="layui-btn layui-btn-danger layui-btn-xs">修改</a>   
            										     <a  data-url="' . Url::build("Menu/delete", ["id" => $r['id']]).'" class="layui-btn layui-btn-primary layui-btn-xs J_list_delete" >删除</a> ';
			$result[$n]['status'] = $r['status'] ? "显示" : "隐藏";
			if(config("app_debug")){
				$result[$n]['app']=$r['app']."/".$r['model']."/".$r['action'];
			}
		}
		$tree->init($result);
		if(config("app_debug")){
			$str = "<tr id='node-\$id' \$parentid_node>
					<td style='padding-left:20px;'><input name='listorders[\$id]' type='text' size='3' value='\$listorder' style='width:35px;height:23px;'></td>
					<td>\$id</td>
        			<td style='text-align:left;'>\$app</td>
					<td style='text-align:left;'>\$spacer <i class='\$icon'></i>\$name</td>
				    <td >\$status</td>
					<td >\$str_manage</td>
				</tr>";
		}else{
			$str = "<tr id='node-\$id' \$parentid_node>
					<td style='padding-left:20px;'><input name='listorders[\$id]' type='text' size='3' value='\$listorder' style='width:35px;height:23px;'></td>
					<td style='text-align:left;'>\$spacer\$name</td>
				</tr>";
		}
		$categorys = $tree->get_tree(0, $str);

        $this->assign("categorys", $categorys);
		$this->assign("app_debug", config("app_debug"));
		return $this->fetch();
	}

	/**
	 * 获取菜单深度
	 * @param $id
	 * @param $array
	 * @param $i
	 */
	protected function _get_level($id, $array = array(), $i = 0) {

		if ($array[$id]['parentid']==0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid']==$id){
			return  $i;
		}else{
			$i++;
			return $this->_get_level($array[$id]['parentid'],$array,$i);
		}
	}

	/**
	 *  添加
	 */
	public function add() {
		if(!C("app_debug")){
			$this -> redirect(Url::build('menu/index'));
		}
		if (IS_POST) {
			$parentid = input("post.parentid");
			$app = input("post.app");
			$model = input("post.model");
			$action = input("post.action");
			$count = Db::name("menu") -> where(['app'=>$app,'model'=>$model,'action'=>$action]) -> count();
			if($count){
				$this -> error("已存在同样的记录，禁止重复添加！");
			}
			if (model("Menu")->save()!==false) {
				$name = strtolower("$app/$model/$action");
				$menu_name = input("post.name");
				$mwhere = array("name"=>$name);
				$find_rule = DB::name("auth_rule")->where($mwhere)->find();
				if(!$find_rule){
				    if($parentid){
                        $menu_url= Db::name("menu") -> where(["id"=>$parentid])->field("app,model,action")->find();
                        $menu_url=strtolower("$menu_url[app]/$menu_url[model]/$menu_url[action]");
                        $parentid=Db::name("auth_rule")->where(["name"=>$menu_url])->value("id");
                    }else{
                        $parentid=0;
                    }
					DB::name("auth_rule") -> insert(["name"=>$name,"module"=>$app,"type"=>"admin_url","title"=>$menu_name,"parentid"=>$parentid]);
				}
				$to=empty($_SESSION['admin_menu_index'])?"Menu/index":$_SESSION['admin_menu_index'];
				adminLog2("添加新菜单: ".$menu_name);
				$this->success("添加成功！", url($to));
			} else {
				$this->error("添加失败！");
			}
		}else{
			$tree = new \think\Tree();
			$parentid = intval(input("parentid"));
			$result = DB::name("menu") ->where(['app'=>'Htsoft'])  -> order(array("listorder" => "ASC"))->select();
			foreach ($result as $r) {
				$r['selected'] = $r['id'] == $parentid ? 'selected' : '';
				$array[] = $r;
			}
			$str = "<option value='\$id' \$selected>\$spacer \$name</option>";
			$tree->init($array);
			$select_categorys = $tree->get_tree(0, $str);
			$this->assign("select_categorys", $select_categorys);
			return $this->fetch();
		}
	}


	/**
	 *  删除
	 */
	public function delete() {
		if(!C("app_debug")){
			$this -> redirect(Url::build('menu/index'));
		}
		$id = intval(input("id"));
		$count = DB::name("menu") -> where(['app'=>'Htsoft','parentid'=>$id]) ->count();
		if ($count > 0) {
			$this->error("该菜单下还有子菜单，无法删除！");
		}
		$menu_url= Db::name("menu")->field("app,model,action")->find($id);
		if (DB::name("menu")->delete($id) !== false) {
			adminLog2("删除菜单!");
            $menu_url=strtolower("$menu_url[app]/$menu_url[model]/$menu_url[action]");
            $delectid=Db::name("auth_rule")->where(["name"=>$menu_url])->value("id");
            if($delectid){
                DB::name("auth_rule") -> delete($delectid);
                DB::name("auth_rule")-> where(['module'=>'Htsoft','parentid'=>$delectid]) -> delete();
            }
			$this->success("删除菜单成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	/**
	 *  编辑
	 */
	public function edit() {
		if(!C("app_debug")){
			$this -> redirect(Url::build('menu/index'));
		}
		if (IS_POST) {
            $parentid = input("post.parentid");
			$app = input("post.app");
			$model = input("post.model");
			$action = input("post.action");
			$id = input("post.id");
			$count = Db::name("menu") -> where(['app'=>$app,'model'=>$model,'action'=>$action,'id'=>['neq',$id]]) -> count();
			if($count){
				$this -> error("已存在同样的记录，禁止重复添加！");
			}
			if (model("menu")->isUpdate(true)->save() !== false) {
				$name = strtolower("$app/$model/$action");
				$menu_name = input("post.name");
				$mwhere=array("name"=>$name);
				$find_rule = Db::name("auth_rule") ->where($mwhere)->find();
                if($parentid){
                    $menu_url= Db::name("menu") -> where(["id"=>$parentid])->field("app,model,action")->find();
                    $menu_url=strtolower("$menu_url[app]/$menu_url[model]/$menu_url[action]");
                    $parentid=Db::name("auth_rule")->where(["name"=>$menu_url])->value("id");
                }else{
                    $parentid=0;
                }
				if(!$find_rule){
					Db::name("auth_rule") -> insert(["name"=>$name,"module"=>$app,"type"=>"admin_url","title"=>$menu_name,"parentid"=>$parentid]);//type 1-admin rule;2-user rule
				}else{
					Db::name("auth_rule") -> where($mwhere) -> update(["name"=>$name,"module"=>$app,"type"=>"admin_url","title"=>$menu_name,"parentid"=>$parentid]);//type 1-admin rule;2-user rule
				}
				$this->success("更新成功！",Url::build('Menu/index'));
			} else {
				$this->error("更新失败！");
			}
		}else{

			$tree = new \think\Tree();
			$id = input("id");
            $rs = Db::name("menu")  ->where(['app'=>'Htsoft','id'=>$id])  ->find();
            $result = Db::name("menu")  ->where(['app'=>'Htsoft']) ->order(array("listorder" => "ASC"))->select();
            foreach ($result as $r) {
                $r['selected'] = $r['id'] == $rs['parentid'] ? 'selected' : '';
                $array[] = $r;
            }
            $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
            $tree->init($array);
            $select_categorys = $tree->get_tree(0, $str);
            $this->assign("data", $rs);

            $this->assign("select_categorys", $select_categorys);
            return $this->fetch();
            $parentid = intval(input("parentid"));
            $result = DB::name("menu") ->where(['app'=>'Htsoft'])  -> order(array("listorder" => "ASC"))->select();
            foreach ($result as $r) {
                $r['selected'] = $r['id'] == $parentid ? 'selected' : '';
                $array[] = $r;
            }
            $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
            $tree->init($array);
            $select_categorys = $tree->get_tree(0, $str);
            $this->assign("select_categorys", $select_categorys);
			return $this->fetch();
		}
	}

	//排序
	public function listorders() {
		$posts = input("post.listorders/a");
		foreach($posts as $k=>$v){
			Db::name('menu') -> where(["id"=>$k]) -> update(["listorder"=>$v]);
		}
		$this->success("排序更新成功！");
	}
}

